# import win32api, win32con, win32gui
from base64 import encode
import uuid
from xmlrpc.client import boolean
import yaml
import os
import pyautogui
import time
import datetime  # 导入datetime模块
import threading  # 导入threading模块
from paddleocr import PaddleOCR
from PIL import Image
from PIL import ImageGrab
import cv2
import numpy as np
# 自写外部类
import count
import imgCompare

#一键斗鸡，需要先打开斗鸡页。↓这里可以配置低于多少战力才打，还有黑名单，在count.py文件里，运行时
#如果打输了，会自动加进去，但是不会保留在文件里，所以执行完一次斗鸡需要手动添加
def compareZhanli1(zhanli):
    return zhanli < 66000

# 读取配置文件


def dict2namespace():
    with open('config.yml', 'r', encoding='utf-8') as f:
        data = yaml.load(f, Loader=yaml.FullLoader)
        return data

# 创建截图文件夹


def makdir(path):
    try:
        isExists = os.path.exists(path)
        # 判断是否存在文件夹
        if not isExists:
            # 不存在创建
            os.makedirs(path)
            print(path+'文件夹创建成功！')
    except Exception as e:
        print(e)

# 截图


def grab_screenshot_area(x, y):
    # print(os.getcwd())
    path = os.getcwd()
    makdir(path+'\\pics\\')
    area = (x, y, x+77, y+77)   # 这里是设置截图范围的区域
    shot = ImageGrab.grab(area)
    filename = path+'\\pics\\'+str(uuid.uuid1())+'.png'
    shot.save(filename)
    # print(filename)
    return filename


def grab_screenshot_area1(x, y, x2, y2):
    # print(os.getcwd())
    path = os.getcwd()
    makdir(path+'\\pics\\')
    area = (x, y, x2, y2)   # 这里是设置截图范围的区域
    shot = ImageGrab.grab(area)
    filename = path+'\\pics\\'+str(uuid.uuid1())+'.png'
    shot.save(filename)
    # print(filename)
    return filename


def compare2pics(target, source):
    # print("target:"+target)
    # print("source:"+source)
    img1 = cv2.imread(target)
    img2 = cv2.imread(source)
    hash1 = imgCompare.aHash(img1)
    hash2 = imgCompare.aHash(img2)
    n = imgCompare.cmpHash(hash1, hash2)
    os.remove(source)
    return n > 0.9


def ocrZhanli(filename):
    # need to run only once to download and load model into memory
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
# result = ocr.ocr('pics\\1.png', cls=True)
    result = ocr.ocr(filename, cls=True)
    name = ''
    for line in result:
        for item in line:
            name += (item[1][0])
    os.remove(filename)
    zhanli = 999999999
    try:
        zhanli = float(name.replace('万', ''))
    except:
        zhanli = float(name.replace('亿', ''))*10000
    # print(zhanli)
    return float(zhanli)




def compareZhanli(filename):
    # need to run only once to download and load model into memory
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
# result = ocr.ocr('pics\\1.png', cls=True)
    result = ocr.ocr(filename, cls=True)
    name = ''
    for line in result:
        for item in line:
            name += (item[1][0])
    os.remove(filename)
    zhanli = 999999999
    if (name.find('万') != -1):
        zhanli = float(name.replace('万', ''))
    elif (name.find('亿') != -1):
        zhanli = float(name.replace('亿', ''))*10000

    return zhanli < 5500


def battle():  # 定义方法 
    print('第'+str(count.doujiCount)+"次斗鸡")
    # print('黑名单：'+str(count.blackList))
    # 跳转按钮 进入选人列表
    pyautogui.moveTo(configs['location']['btn']['tiaozhan']
                     ['x'], configs['location']['btn']['tiaozhan']['y'])
    # 跳转按钮
    pyautogui.click()

    time.sleep(2)
    try:
        battles()
    except:
        battle()


def checkBlack(name):
    isBlack = False
    if count.blackList.count(name) > 0:
        isBlack = True
    if isBlack:
        print("黑名单人物："+name)
    return isBlack


def getName(filename):
    # need to run only once to download and load model into memory
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
# result = ocr.ocr('pics\\1.png', cls=True)
    result = ocr.ocr(filename, cls=True)
    name = ''
    for line in result:
        for item in line:
            name += (item[1][0])
    os.remove(filename)
    return name


def battles():  # 定义方法

    # 查黑名单
    x, y, x2, y2 = configs['location']['jietu']['black3']['x'], configs['location']['jietu']['black3'][
        'y'], configs['location']['jietu']['black3']['x2'], configs['location']['jietu']['black3']['y2']
    black3 = grab_screenshot_area1(x, y, x2, y2)
    name3 = getName(black3)
    if (checkBlack(name3) != True):
        # 截图比对第三个战力够不够
        x, y, x2, y2 = configs['location']['jietu']['pvp3']['x'], configs['location']['jietu']['pvp3'][
            'y'], configs['location']['jietu']['pvp3']['x2'], configs['location']['jietu']['pvp3']['y2']
        pvp3 = grab_screenshot_area1(x, y, x2, y2)
        zhanli = ocrZhanli(pvp3)
        print('当前斗鸡,已成功：'+str(count.success)+"个，失败"+str(count.failed)+"个")
        if compareZhanli1(zhanli):
            print(name3+"："+str(zhanli)+"万")
        # 进入战斗
            pyautogui.moveTo(configs['location']['btn']['tiaozhan3']
                             ['x'], configs['location']['btn']['tiaozhan3']['y'])
        # 进入战斗
            pyautogui.click()
            time.sleep(4)
        # # 倍速
        #     pyautogui.moveTo(configs['location']['btn']['speed']
        #                      ['x'], configs['location']['btn']['speed']['y'])
        #     pyautogui.click()
        #     time.sleep(0.5)
        #     pyautogui.click()

        # 比对结果
            isOver = False
            while isOver != True:
                x, y, x2, y2 = configs['location']['jietu']['pvpResult']['x'], configs['location']['jietu']['pvpResult'][
                    'y'], configs['location']['jietu']['pvpResult']['x2'], configs['location']['jietu']['pvpResult']['y2']
                pvpresult = grab_screenshot_area1(x, y, x2, y2)
                isOver = compare2pics('target\\pvpresult.png', pvpresult)
            # 未结束 继续等待
                time.sleep(5)

            x, y, x2, y2 = configs['location']['jietu']['pvpsuccess']['x'], configs['location']['jietu']['pvpsuccess'][
                'y'], configs['location']['jietu']['pvpsuccess']['x2'], configs['location']['jietu']['pvpsuccess']['y2']
            pvpsuccess = grab_screenshot_area1(x, y, x2, y2)
            if compare2pics('target\\pvpsuccess.png', pvpsuccess):
                count.success += 1
            else:
                count.failed += 1
                count.blackList.append(name3)

            count.doujiCount += 1
        # 结束战斗 退出战斗页面
            pyautogui.click()
        # 结束战斗 重新开始
            battle()
            return

    # 查黑名单
    x, y, x2, y2 = configs['location']['jietu']['black2']['x'], configs['location']['jietu']['black2'][
        'y'], configs['location']['jietu']['black2']['x2'], configs['location']['jietu']['black2']['y2']
    black2 = grab_screenshot_area1(x, y, x2, y2)
    name2 = getName(black2)
    if (checkBlack(name2) != True):
     # 截图比对第二个战力够不够
        x, y, x2, y2 = configs['location']['jietu']['pvp2']['x'], configs['location']['jietu']['pvp2'][
            'y'], configs['location']['jietu']['pvp2']['x2'], configs['location']['jietu']['pvp2']['y2']
        pvp2 = grab_screenshot_area1(x, y, x2, y2)
        zhanli = ocrZhanli(pvp2)
    # pvp2battle = compareZhanli1(zhanli)
        if compareZhanli1(zhanli):
            print(name2+"："+str(zhanli)+"万")
        # 进入战斗
            pyautogui.moveTo(configs['location']['btn']['tiaozhan2']
                             ['x'], configs['location']['btn']['tiaozhan2']['y'])
        # 进入战斗
            pyautogui.click()
            time.sleep(4)
        # 倍速
            # pyautogui.moveTo(configs['location']['btn']['speed']
            #                  ['x'], configs['location']['btn']['speed']['y'])
            # pyautogui.click()
            # time.sleep(0.5)
            # pyautogui.click()

        # 比对结果
            isOver = False
            while isOver != True:
                x, y, x2, y2 = configs['location']['jietu']['pvpResult']['x'], configs['location']['jietu']['pvpResult'][
                    'y'], configs['location']['jietu']['pvpResult']['x2'], configs['location']['jietu']['pvpResult']['y2']
                pvpresult = grab_screenshot_area1(x, y, x2, y2)
                isOver = compare2pics('target\\pvpresult.png', pvpresult)
            # 未结束 继续等待
                time.sleep(5)

            x, y, x2, y2 = configs['location']['jietu']['pvpsuccess']['x'], configs['location']['jietu']['pvpsuccess'][
                'y'], configs['location']['jietu']['pvpsuccess']['x2'], configs['location']['jietu']['pvpsuccess']['y2']
            pvpsuccess = grab_screenshot_area1(x, y, x2, y2)
            if compare2pics('target\\pvpsuccess.png', pvpsuccess):
                count.success += 1
            else:
                count.failed += 1
                count.blackList.append(name2)
            count.doujiCount += 1
        # 结束战斗 退出战斗页面
            pyautogui.click()
        # 结束战斗 重新开始
            battle()
            return

    # 查黑名单
    x, y, x2, y2 = configs['location']['jietu']['black1']['x'], configs['location']['jietu']['black1'][
        'y'], configs['location']['jietu']['black1']['x2'], configs['location']['jietu']['black1']['y2']
    black1 = grab_screenshot_area1(x, y, x2, y2)
    name1 = getName(black1)
    if (checkBlack(name1) != True):
       # 截图比对第一个战力够不够
        x, y, x2, y2 = configs['location']['jietu']['pvp1']['x'], configs['location']['jietu']['pvp1'][
            'y'], configs['location']['jietu']['pvp1']['x2'], configs['location']['jietu']['pvp1']['y2']
        pvp1 = grab_screenshot_area1(x, y, x2, y2)
        zhanli = ocrZhanli(pvp1)
    # pvp1battle = compareZhanli1(zhanli)
        if compareZhanli1(zhanli):
            print(name1+"："+str(zhanli)+"万")
        # 进入战斗
            pyautogui.moveTo(configs['location']['btn']['tiaozhan1']
                             ['x'], configs['location']['btn']['tiaozhan1']['y'])
        # 进入战斗
            pyautogui.click()
            time.sleep(4)
        # 倍速
            # pyautogui.moveTo(configs['location']['btn']['speed']
            #                  ['x'], configs['location']['btn']['speed']['y'])
            # pyautogui.click()
            # time.sleep(0.5)
            # pyautogui.click()

        # 比对结果
            isOver = False
            while isOver != True:
                x, y, x2, y2 = configs['location']['jietu']['pvpResult']['x'], configs['location']['jietu']['pvpResult'][
                    'y'], configs['location']['jietu']['pvpResult']['x2'], configs['location']['jietu']['pvpResult']['y2']
                pvpresult = grab_screenshot_area1(x, y, x2, y2)
                isOver = compare2pics('target\\pvpresult.png', pvpresult)
            # 未结束 继续等待
                time.sleep(5)

            x, y, x2, y2 = configs['location']['jietu']['pvpsuccess']['x'], configs['location']['jietu']['pvpsuccess'][
                'y'], configs['location']['jietu']['pvpsuccess']['x2'], configs['location']['jietu']['pvpsuccess']['y2']
            pvpsuccess = grab_screenshot_area1(x, y, x2, y2)
            if compare2pics('target\\pvpsuccess.png', pvpsuccess):
                count.success += 1
            else:
                count.failed += 1
                count.blackList.append(name1)
            count.doujiCount += 1
        # 结束战斗 退出战斗页面
            pyautogui.click()
        # 结束战斗 重新开始
            battle()
            return

    # 三个都不小于六千万战力的话 就需要刷新一下
     # 刷新按钮
    pyautogui.moveTo(configs['location']['btn']['refresh']
                     ['x'], configs['location']['btn']['refresh']['y'])
    # 刷新按钮
    pyautogui.click()
    time.sleep(0.5)
    # 递归调用
    battles()


if __name__ == "__main__":
    configs = dict2namespace()
    # t1 = threading.Timer(1, function=job)  # 创建定时器
    # t1.start()  # 开始执行线程
    battle()
